const app = getApp();
var interval0;
var interval1;
var interval2;
var interval3;
var interval4;
var interval5;
var interval6;
var interval7;
var interval8;
var interval9;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bodyHeight: 0,
		isHiddenrefuseOrderReason: true,
		refuseForm: {
			reason: '',
			id: 0
		},//拒接单理由和id
		isHiddencancelOrderReason: true,
		cancelForm: {
			reason: '',
			id: 0
		},//取消订单理由和id
		currentTab: 1,
		/* 自定义导航栏参数 */
		loading: false,
		color: '#000000',
		background: '#FFFFFF',
		show: true,
		animated: false,
		back: false,
		title: "我的订单",
		/* 自定义tabbar */
		list: [
			{
		        "pagePath": "/page/index/index",
		        "iconPath": "/images/index.png",
		        "selectedIconPath": "/images/index-selected.png",
		        "text": "抢单"
		    },
		    {
		        "pagePath": "/page/order_list/index",
		        "iconPath": "/images/timetable.png",
		        "selectedIconPath": "/images/timetable-selected.png",
		        "text": "订单"
		    },
		    
		    {
		        "pagePath": "/page/mine/mine",
		        "iconPath": "/images/mine.png",
		        "selectedIconPath": "/images/mine-selected.png",
		        "text": "我的"
		    },
		],
		/* 订单筛选 */
		status: 1,//0=待接单,1=待上门,2=回收中,3=已完成,4=已评价,
		orderList:[],
		orderInterval: ''
	},
	tabChange(e) {
		wx.removeStorageSync('isRecording');
		wx.removeStorageSync('recordingTime');
		wx.reLaunch({
		  url: e.detail.item.pagePath
		})
	},
	swichNav: function( e ) {
		var that = this; 
		if( that.data.status === e.target.dataset.status ) {
			return false;
		} else { 
			that.setData( { 
				status: e.target.dataset.status
			})
		}
		that.orderList(that.data.status);
	},
	orderList: function(status){
		var that = this;
		clearTimeout(interval0);
		clearTimeout(interval1);
		clearTimeout(interval2);
		clearTimeout(interval3);
		clearTimeout(interval4);
		clearTimeout(interval5);
		clearTimeout(interval6);
		clearTimeout(interval7);
		clearTimeout(interval8);
		app.request('/api/timetable.user/orderList', {status: status}, function (data, ret) {
		  that.setData({
		    orderList: data,
		  });
			that.data.orderList.forEach(function(item,index){
				//计算剩余时间或者超时时间  正数为剩余 负数为超时
				that.count_down(item.remaintime, index);
			})
		}, function (data, ret) {
		  app.error('服务器错误');
		});
	},
	count_down: function(remaintime, index) {
			var that = this;
			var expireMs = remaintime;
			if(that.data.orderList.hasOwnProperty(index)){
				that.setData({
					 ['orderList['+index+'].remaintime_text']: that.date_format(expireMs),
				});
			}
			if( index==0 ){
				interval0 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==1 ){
				interval1 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==2 ){
				interval2 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==3 ){
				interval3 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==4 ){
				interval3 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==5 ){
				interval3 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==6 ){
				interval6 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==7 ){
				interval7 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
			if( index==8 ){
				interval8 = setTimeout(function() {
					 expireMs = expireMs - 1;
					 that.count_down(expireMs,index);
				}, 1000)
			}
	 },
	/* 格式化倒计时 */
	date_format: function(seconds) {
		if(seconds < 0) seconds = seconds*(-1);
		var that = this;
		// var day = that.fill_zero_prefix(Math.floor(seconds / 86400)) //天
		var folur = that.fill_zero_prefix(Math.floor((seconds % 86400) / 3600))//小时
		var min = that.fill_zero_prefix(Math.floor((seconds % 3600) / 60));// 分钟位
		var sec = that.fill_zero_prefix(seconds % 60); // equal to => var sec = second % 60;// 秒位
		return folur+':'+min+':'+sec;
	},
	fill_zero_prefix: function(num) {
		return num < 10 ? "0" + num : num
	},
	onLoad: function () {
	  var that = this;
		that.setData({
			cdnUrl: app.cdnUrl,
		});
	},
	onShow: function (){
		var that = this;
    try {
      var status = wx.getStorageSync('order_list_status');
      if (status==2) {
        try {
          wx.removeStorageSync('order_list_status');
          that.setData({
            status: 2,
          });
        } catch (e) {
          // Do something when catch error
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    that.orderList(that.data.status);
		var bodyHeight = (667-180)*750/app.globalData.windowWidth*(app.globalData.windowHeight/667);
		that.setData({
		  bodyHeight: bodyHeight,
		});
		// if (app.globalData.userInfo) {
		// 	// that.orderList(that.data.status);//获取订单列表 0为默认全部订单
		//   that.setData({ 
		//     userInfo: app.globalData.userInfo,
		//   });
		// }else{
		// 	app.check(that);
		// }
		if (app.globalData.userInfo) {
		  that.getUserInfo();
			if(!app.globalData.userInfo.rider_apply){
				app.showApply();
				return false;
			}else{
		    if(app.globalData.userInfo.rider_apply.status == 0 || app.globalData.userInfo.rider_apply.status == 2){
		      app.showApply();
		      return false;
		    }
		  }
      that.orderList(that.data.status);//获取订单列表 0为默认全部订单
			// that.MapContext = wx.createMapContext('myMap');
		  that.setData({ 
		    userInfo: app.globalData.userInfo,
		  });
		}else{
			setTimeout(function () {
				if (app.globalData.userInfo) {
					wx.reLaunch({
						url: '/page/order_list/index'
					});
				}else{
					app.check(function(ret){}, '/page/order_list/index');
				}
			}, 500)
		}
	},
	onPullDownRefresh: function () {
		this.orderList(this.data.status);
	},
	onReachBottom: function () {},
	
	onShareAppMessage: function () {
	  return {
	    title: '',
	    desc: '',
	    path: '/page/index/index'
	  }
	},
	/* 接单 */
	receivingOrder: function(e){
		var that = this;
		var currenId = e.currentTarget.dataset.id;
		var currenOrder =  {};
		that.data.orderList.forEach(function (item) {
			if(item.id == currenId){
				currenOrder = item;
			}
		})
		app.request('/api/timetable.user/receivingOrder', {id:currenId,distance:currenOrder.grabbing_distance}, function (data, ret) {
      that.orderList(that.data.status);
		  app.error(ret.msg);
		}, function (data, ret) {
		  app.error(ret.msg);
			that.orderList(that.data.status);
		});
	},
	/* 拒绝接单理由弹窗 */
	refuseOrderModal: function(e){
		var that = this;
		that.setData({
			isHiddenrefuseOrderReason: false,
			['refuseForm.id']: e.currentTarget.dataset.id
		})
	},
	refuseOrderModalHidden: function(){
		var that = this;
		that.setData({
			isHiddenrefuseOrderReason: true,
		})
	},
	refuseReasonChange: function(e){
		var value = e.detail.value;
		this.setData({
			['refuseForm.reason']: value,
		})
	},
	/* 拒绝接单提交 */
	refuseOrder: function(){
		var that = this;
		if(that.data.refuseForm.reason==''){
			app.error('请输入理由');
			return false;
		}
		if(that.data.refuseForm.id==0){
			app.error('请选择订单');
			return false;
		}
		app.request('/api/timetable.user/refuseOrder', that.data.refuseForm, function (data, ret) {
			that.orderList(that.data.status);
		  app.error(ret.msg);
			that.setData({
				isHiddenrefuseOrderReason: true,
			})
		}, function (data, ret) {
		  app.error(ret.msg);
			return false;
		});
	},
	/* 达到送件 */
	arriveOrder: function (e){
		var that = this;
		var id = e.currentTarget.dataset.id;
		app.request('/api/timetable.user/arriveOrder', {id: id}, function (data, ret) {
			that.orderList(that.data.status);
		  app.error(ret.msg);
		}, function (data, ret) {
		  app.error(ret.msg);
			return false;
		});
	},
	
	/* 取消订单理由弹窗 */
	cancelOrderModal: function(e){
		var that = this;
		that.setData({
			isHiddencancelOrderReason: false,
			['cancelForm.id']: e.currentTarget.dataset.id
		})
	},
	cancelOrderModalHidden: function(){
		var that = this;
		that.setData({
			isHiddencancelOrderReason: true,
		})
	},
	cancelReasonChange: function(e){
		var value = e.detail.value;
		this.setData({
			['cancelForm.reason']: value,
		})
	},
	/* 取消订单操作 */
	cancelOrder:function(){
		var that = this;
		if(that.data.cancelForm.reason==''){
			app.error('请输入理由');
			return false;
		}
		if(that.data.cancelForm.id==0){
			app.error('请选择订单');
			return false;
		}
		app.request('/api/timetable.user/cancelOrder', that.data.cancelForm, function (data, ret) {
			that.orderList(that.data.status);
		  app.error(ret.msg);
			that.setData({
				isHiddencancelOrderReason: true,
			})
		}, function (data, ret) {
		  app.error(ret.msg);
			return false;
		});
	},
  /* 订单入库*/
  storageOrder: function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    /* 拉起扫一扫*/
    wx.scanCode({
      onlyFromCamera: true,
      success (res) {
        console.log(res)
        /* 回收站id 从二维码中获取*/
        var pack_station_id = parseInt(res.result);
        if( isNaN(pack_station_id)){
          app.error("二维码错误");
          return false;
        }
        app.request('/api/timetable.user/storageOrder', {id: [id], pack_station_id: pack_station_id}, function (data, ret) {
        	that.orderList(that.data.status);
          app.error(ret.msg);
        }, function (data, ret) {
          app.error(ret.msg);
        	return false;
        });
      },
      // fail (){
      //   app.error("入库失败，请重试");
      //   return false;
      // }
    })
  },
  /* 获取用户信息*/
  getUserInfo: function(){
    var that = this;
    app.request("/api/timetable.user/userInfo", {}, function (data, ret) {
      // app.success('头像上传成功!');
      app.globalData.userInfo = data.userInfo;
      that.setData({
        userInfo: data.userInfo
      });
    }, function (data, ret) {
      // app.error(ret.msg);
    });
  }
})